package com.newlink.building.userinfo.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.base.NL_OnActivityCallback
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.Base_AddFamilyManagementBean
import com.newlink.building.common_base.model.bean.AddFamilyManagementData
import com.newlink.building.common_base.model.bean.CountryCodeBean
import com.newlink.building.common_base.model.bean.FamilyManagementListData1
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.RegexUtils
import com.newlink.building.common_base.utils.countrycode.Base_CountryCodeSelectActivityNL
import com.newlink.building.common_base.widget.CustomInputDialog
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.databinding.ActivityFamilyManagementAddBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_FamilyManagementAddPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_FamilyManagementAddContract
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.jetbrains.anko.textColor
import org.json.JSONArray
import java.io.Serializable

/**
 * @author wangyang
 * @date 2022/10/11
 * @description 我的——家庭管理页面——添加家庭成员页面
 */
class Module_UserInfo_FamilyManagementAddActivityNL :
    NL_BaseMvpActivity<Module_UserInfo_FamilyManagementAddContract.View, Module_UserInfo_FamilyManagementAddContract.Presenter>(),
    Module_UserInfo_FamilyManagementAddContract.View {

    private var countryCodeList = mutableListOf<CountryCodeBean>()
    private var mDefaultCountryCodeBean: CountryCodeBean? = null
    private var needUpdateEmail = false
    var mInputDialog: CustomInputDialog? = null
    var mCountryCode: String = ""

//    override fun attachLayoutRes(): Int = R.layout.activity_family_management_add

    private lateinit var mBinding: ActivityFamilyManagementAddBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityFamilyManagementAddBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        loadDefaultCountryCode()
        checkPrimaryEmail()
    }

    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this)
    }

    override fun hideLoading() {
        if (!needUpdateEmail) {
            mDialog.hide()
        }
    }

    override fun showLoading() {
        mDialog.setCancelable(false)
        mDialog.show()
    }

    override fun initView() {
        super.initView()
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.family_management_add_title)
        mCountryCode = countryCode
        mBinding.btnCountryCode.text = "+$countryCode"

        mBinding.tvDescribeTips.text =
            getString(R.string.kit_family_management_add_describe_username, "${maxUserCount - 1}")
        mBinding.tvDescribeTips.text = getString(
            if (userInfoData.userCategory == 2) R.string.kit_family_management_add_describe_username else R.string.family_management_add_describe_username,
            "${maxUserCount - 1}"
        )
//        mBinding.keySymbolEmail.visibility = if(userInfoData.userCategory == 2) View.VISIBLE else View.GONE

//        mBinding.tvEmailDescribe.text = if(userInfoData.email.isNotEmpty()) "(${getString(R.string.account_information_email_descrive)})" else ""
        mBinding.btnCountryCode.setOnClickListener {
            val intent =
                Intent(this@Module_UserInfo_FamilyManagementAddActivityNL, Base_CountryCodeSelectActivityNL::class.java)
            intent.putExtra("default_country", mDefaultCountryCodeBean)
            intent.putExtra("country_list", countryCodeList as Serializable)
            startActivityForResult(intent, object : NL_OnActivityCallback {
                @SuppressLint("SetTextI18n")
                override fun onActivityResult(resultCode: Int, data: Intent?) {
                    if (resultCode == 1_000_008) {
                        val defaultCountryCode = data?.getStringExtra("default_country_code")
                        if (defaultCountryCode?.isNotEmpty() == true) {
                            mBinding.btnCountryCode.text = "+ $defaultCountryCode"
                            countryCode = defaultCountryCode
                            mCountryCode = defaultCountryCode
                        }
                    }
                }

            })
        }

        mBinding.btnSubmit.setOnClickListener {
            var inputEmail = mBinding.etEmail.text.toString()
            if (inputEmail.isNotEmpty()) {
                if (!RegexUtils.checkEmail(inputEmail) && !RegexUtils.checkEmail2(inputEmail)) {
                    showToast(getString(R.string.regex_email_error_format))
                    return@setOnClickListener
                }
//                needUpdateEmail = true
            } else {
                inputEmail = ""
            }

            var phoneNumber = mBinding.etPhone.text.toString().ifEmpty { "" }
            if (phoneNumber.isNotEmpty()) {
                if (!RegexUtils.checkCommonPhoneNumber(phoneNumber)) {
                    showToast(getString(R.string.regex_phone_error_format))
                    return@setOnClickListener
                }
            } else {
                phoneNumber = ""
            }
            if (needUpdateEmail) {
                mPresenter?.updateEmail(accessToken, userId, inputEmail)
                showLoading()
            } else {
                startWork(inputEmail, phoneNumber)
            }

        }

        //用户名输入框监听
        mBinding.etUsername.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkSubmitState()
            }
        })

        mBinding.etEmail.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkSubmitState()
            }

        })

        //邮箱输入框监听
        mBinding.etEmail.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                checkSubmitState()
            }
        })
    }

    override fun createPresenter(): Module_UserInfo_FamilyManagementAddContract.Presenter =
        Module_UserInfo_FamilyManagementAddPresenter()

    override fun addFamilyManagementSuccess(data: AddFamilyManagementData?) {
        showToast(getString(R.string.default_add_success))
        needUpdateEmail = false
        hideLoading()
        if (mBinding.cbQrCode.isChecked) {
            val data = FamilyManagementListData1(id = data?.id.orEmpty())
            Module_UserInfo_FamilyManagementDetailWaitActivationQRCodeActivityNL.startSelf(this, data)
        }
        finish()
    }

    override fun addFamilyManagementFail() {
        showToast(getString(R.string.default_add_fail))
        needUpdateEmail = false
        hideLoading()
    }

    override fun updateEmailSuccess(success: Boolean, email: String) {
        if (success) {
            mInputDialog?.dismiss()
            val mUserInfoData = userInfoData
            mUserInfoData.email = email
            userInfoData = mUserInfoData
        } else {
            showToast(getString(R.string.default_add_fail))
            hideLoading()
        }
    }

    private fun startWork(inputEmail: String, phoneNumber: String) {
        val addFamilyManagementBean = Base_AddFamilyManagementBean(
            mBinding.etUsername.text.toString(),
            inputEmail,
            mBinding.cbQrCode.isChecked,
            userId,
            phoneNumber,
            mCountryCode.ifEmpty { countryCode },
            prjType = userInfoData.prjType
        )

        mPresenter?.addFamilyManagement(accessToken, addFamilyManagementBean, userInfoData.prjType)
        showLoading()
    }

    /**
     * 核验提交按钮的状态
     * 当用户名和邮箱不为空时，可以提交
     */
    fun checkSubmitState() {
        val inputUsername = mBinding.etUsername.text.trim().toString()
        val inputEmail = mBinding.etEmail.text.trim().toString()

//        if(userInfoData.userCategory == 2) {
//            mBinding.btnSubmit.isEnabled = inputUsername.isNotEmpty() && inputEmail.isNotEmpty()
//        } else {
        mBinding.btnSubmit.isEnabled = inputUsername.isNotEmpty()
        mBinding.btnSubmit.textColor =
            if (mBinding.btnSubmit.isEnabled) getColor(R.color.white) else getColor(R.color.disabled_text_color)
//        }

    }

    fun checkPrimaryEmail(): Boolean {
        if (userInfoData.email.isEmpty()) {
            mInputDialog = CustomInputDialog(this)
            mInputDialog!!.setTitle(getString(R.string.family_management_title_set_email))
                .setPositiveButton(
                    getString(R.string.family_management_email_to_bind),
                    object : CustomInputDialog.OnClickListener {
                        override fun onClick(type: Int, inputEmail: String) {
                            if (!RegexUtils.checkEmail(inputEmail) && !RegexUtils.checkEmail2(
                                    inputEmail
                                )
                            ) {
                                showToast(getString(R.string.regex_email_error_format))
                                return
                            }
                            mPresenter?.updateEmail(accessToken, userId, inputEmail)
                        }

                    })
                .setNegativeButton(
                    getString(R.string.title_bar_back),
                    object : CustomInputDialog.OnClickListener {
                        override fun onClick(type: Int, inputText: String) {
                            mInputDialog!!.dismiss()
                            finish()
                        }
                    })
            mInputDialog?.show()
            mInputDialog?.setCancelable(false)
        }
        return false
    }

    private fun loadDefaultCountryCode() {
        val countryCode = resources.configuration.locale.country
        NLog.e("[jake] .. country Code is $countryCode")
        val countryCodeJson = StringBuffer()

        lifecycleScope.launch(Dispatchers.IO) {
            applicationContext.assets.open("country.json").bufferedReader().use { reader ->
                reader.forEachLine {
                    countryCodeJson.append(it)
                }
            }
            val ja = JSONArray(countryCodeJson.toString())
            for (i in 0 until ja.length()) {
                ja.getJSONObject(i).let {
                    val countryCodeBean = CountryCodeBean(
                        it.getString("locale"),
                        it.getString("area"),
                        it.getString("code")
                    )
                    countryCodeList.add(countryCodeBean)
                }
            }

            withContext(Dispatchers.Main) {
                if (countryCodeList.size > 0) {
                    val countryCodeBean = countryCodeList.find {
                        it.locale == countryCode
                    }
                    if (countryCodeBean != null) {
//                        country_code_btn.text = "+"+countryCodeBean.code
                        mDefaultCountryCodeBean = countryCodeBean
                    }
                }
            }

        }
    }
}